import { defineStore } from "pinia";
import { reqLogin, backLoginAPI } from "@/api/user";
import type { loginForm, reqRespones } from "@/api/user/type";
import router from "@/routes";

import { setToken, getToken } from "@/utils/token";
import { conRoutes, asyncRoutes, anyRoutes } from "../../routes/routes";
import { reqUserInfo } from "../../api/user/index";
import { useRoute } from "vue-router";
import cloneDeep from "lodash/cloneDeep";

// import { useRouter } from "vue-router";

function filterHasRoutes(asnycRoute: any, routes: any) {
    return asnycRoute.filter((item: any) => {
        if (routes.includes(item.name)) {
            if (item.children && item.children.length > 0) {
                item.children = filterHasRoutes(item.children, routes);
            }
            return true;
        }
    });
}
export const useUserStore = defineStore("user", {
    state: () => {
        return {
            token: getToken(),
            menuRoutes: conRoutes,
            userName: "",
            avatar: "1111",
            buttons:[]
        };
    },
    actions: {
        async useLogin(data: loginForm) {
            let req: reqRespones = await reqLogin(data);

            if (req.code == 200) {
                setToken(req);
                this.token = req.data as string;
                // localStorage.setItem("TOKEN",req.data.token as string)
                //登录成功跳转
                // router.push("/");
                // 返回成功的promise
                return "ok";
            } else {
                // 失败返回错误的message
                return Promise.reject(req.data);
            }
        },

        async userInfo() {
            let userInfoDate: any = await reqUserInfo();
            if (userInfoDate.code == 200) {
                this.userName = userInfoDate.data.name;
                this.avatar = userInfoDate.data.avatar;
                this.buttons = userInfoDate.data.buttons;

                //计算当前用户需要展示的异步路由
                const userAsyncRoute = filterHasRoutes(
                    cloneDeep(asyncRoutes),
                    userInfoDate.data.routes
                );
                // 菜单需要的数据整理完毕
                // 展示路由
                this.menuRoutes = [...conRoutes, ...userAsyncRoute, anyRoutes];

                //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
                [...userAsyncRoute, anyRoutes].forEach((route: any) => {
                    router.addRoute(route);
                });
                return "ok";
            } else {
                return Promise.reject("获取失败");
            }
        },

        async backLogin() {
            let backInfo: any = await backLoginAPI();

            if (backInfo.code == 200) {
                // router.push({ path: "/login" });
                localStorage.removeItem("TOKEN");
                this.userName = "";
                this.avatar = "";
                this.token = "";
                return "ok";
            }
        },
    },
});
